import {Component, EventEmitter, Input, OnInit, Optional, Output, Self, ViewChild} from '@angular/core';
import {FormControlName} from '@angular/forms';
import {timer} from 'rxjs';

@Component({
  selector: 'ng-tools-file-upload',
  templateUrl: './file-upload.component.html',
  styleUrls: ['./file-upload.component.scss']
})
export class FileUploadComponent implements OnInit {
  @Input() multi = false;
  @Input() isError = '';
  @Input() uploadProgress = 0;
  @Output() fileSelected = new EventEmitter();
  @ViewChild('fileInput') fileInput;
  file: {
    name: string;
    size: number;
  } | any;

  fileSize: string;
  constructor(@Optional() @Self() private formControlName: FormControlName) {
  }

  ngOnInit() {
    if (this.formControlName) {
      this.formControlName.control.valueChanges.subscribe((next) => {
        timer(0).subscribe(() => {
          this.reset();
        });
      });
    }
  }

  reset() {
    this.fileInput.nativeElement.value = null;
    this.file = null;
    this.uploadProgress = 0;
    this.fileSize = null;
  }

  browseFile() {
    this.fileInput.nativeElement.click();
  }

  selectFile(e) {
    this.isError = '';
    e.stopPropagation();
    this.uploadProgress = 0;
    const fileList = e.target.files;
    if (fileList.length > 0) {
      this.file = fileList[0];
      const size = fileList[0].size;
      if (size > 1024) {
        this.fileSize = Math.floor(fileList[0].size / 1024) + 'kb';
      } else {
        this.fileSize = size + '字节';
      }
      this.fileSelected.emit(this.file);
    }
  }
}


